import { defineStore } from 'pinia'
import $axios from "../plugins/http"
import axios from "axios"

/* const modules = import.meta.globEager('./modules/*.ts');

for (const key in modules) {
  let str: string = key.replace(/(\.\/modules\/|\.ts)/g, '');
  str = str[0].toUpperCase() + str.slice(1) + 'Module';
  modules[str] = modules[key].default;
  Reflect.deleteProperty(modules, key);
} */

export const usePinia = defineStore('index', {
  // 推荐使用 完整类型推断的箭头函数
  state: () => ({
    loginBkImg: '', // 登录页面的背景图片
    registerBkImgs: [] as Array<{
      id: number;
      url: string;
    }>, // 注册页面的背景图片集合
    codeUrl: '', // 验证码图片的url
    searchHistory: [] as Array<string>,
  }),
  actions: {
    // 请求缓存(缓存的聊天记录、好友信息等)
    async clearCache(payload: { callback: (...arg: any[]) => any }): Promise<boolean> {
      const { useMessagePinia } = await import("@/pinia/messages");
      const { useFriendPinia } = await import("@/pinia/friend");
      const { useDynamicPinia } = await import("@/pinia/dynamic");
      const messageStore = useMessagePinia();
      const friendStore = useFriendPinia();
      const dynamicStore = useDynamicPinia();
      return new Promise<boolean>(resolve => {
        payload.callback();
        setTimeout(() => {
          for (const value of messageStore.chatList.values()) {
            if (value.isRequMessRecord) value.isRequMessRecord = false;
            if (value.messagesDatas.size) value.messagesDatas.clear();
          }
          if (friendStore.isRequGetAllFriend) friendStore.isRequGetAllFriend = false;
          friendStore.friends.size && friendStore.friends.clear();
          friendStore.friendsInfos.size && friendStore.friendsInfos.clear();
          dynamicStore.dynamicDatas.value.size && dynamicStore.dynamicDatas.value.clear();
          dynamicStore.dynamicDatas.isRequest = false;
          dynamicStore.dynamicDatas.isReload = false;
          dynamicStore.mySelfDynamicDatas.value.size && dynamicStore.mySelfDynamicDatas.value.clear();
          dynamicStore.mySelfDynamicDatas.isRequest = false;
          dynamicStore.mySelfDynamicDatas.isReload = false;
          if (friendStore.isRequFriendsManage) friendStore.isRequFriendsManage = false;
          for (const item of friendStore.friendsManage.values()) {
            if (item.noGroups?.isRequest) item.noGroups.isRequest = false;
            if (item.noGroups?.friends.size) item.noGroups.friends.clear();
            if (item.groups?.size) item.groups.clear();
          }
          resolve(true);
        })
      })
    },
    // 获取登录页面的背景图片
    async getLoginBkImg(): Promise<number> {
      if (this.loginBkImg) this.loginBkImg = '';
      return await $axios(
        ['/getImage/login'],
        ({ url }): void => {
          new Image().src = url;
          this.loginBkImg = url
        },
      );
    },
    // 获取注册页面的背景图片集合
    async getRegisterBkImgs(): Promise<number> {
      return await $axios(
        ['/getImage/register'],
        (imgs): void => {
          const image = new Image();
          imgs.forEach((url: string) => image.src = url);
          this.registerBkImgs = imgs
        },
      );
    },
    // 请求验证码接口
    getVerCode(): Promise<number> {
      return new Promise<number>((resolve, reject) => {
        axios.get("/api/user/code").then((res: any) => {
          if (res.data.code === 1) {
            const { value, key } = res.data.data;
            sessionStorage.setItem('codeKey', key);
            this.codeUrl = `data:image/png;base64,${value}`;
            resolve(1);
          } else {
            console.log(res.msg);
            resolve(0);
          }
        }).catch((error) => {
          console.log(error);
          reject();
        });
      });
    },
    // 获取用户的搜索历史记录
    async getSearchHistory(): Promise<number> {
      return await $axios(
        ['/search/getSearchHistory', 'post', undefined, true],
        ({ keywords }) => this.searchHistory.unshift(...keywords),
      );
    },
    // 清空搜索历史记录
    async clearSearchHistory(): Promise<number> {
      return await $axios(
        ['/search/clearSearchHistory', 'get'],
        () => this.searchHistory.splice(0),
      );
    },
    // 删除某条历史记录
    async deleteSearchHistory(payload: { value: string }): Promise<number> {
      return await $axios(
        ['/search/deleteSearchHistory', 'post', { data: payload.value }],
        () => {
          const index: number = this.searchHistory.findIndex(item => item === payload.value);
          this.searchHistory.splice(index, 1);
        }
      );
    },
    // 获取用户搜索的结果
    getSearchResult(payload: { keyword: string }): Promise<{
      code: number;
      userList: Array<User & { isFriend: boolean; bkImg: string; }>;
    }> {
      let users: Array<User & { isFriend: boolean; bkImg: string; }> = [];
      return new Promise<{
        code: number;
        userList: Array<User & { isFriend: boolean; bkImg: string; }>;
      }>((resolve, reject) => {
        $axios(
          ['/search/getSearchResult', 'post', { keyword: payload.keyword }, true],
          ({ userList }) => users = userList,
        ).then((code) => resolve({
          code,
          userList: users as Array<User & { isFriend: boolean; bkImg: string; }>,
        })).catch(() => reject())
      })
    },
  },
})